package com.haiertvbic.tvwa;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.haiertvbic.tvnow.R;
import com.haiertvbic.tvnow.model.LocalCodeBean;
import com.haiertvbic.tvnow.model.ProgramBean;
import com.haiertvbic.tvnow.model.SingleHandler;
import com.haiertvbic.tvnow.network.EPGWeb;
import com.haiertvbic.tvnow.protocol.CAEProtocol;
import com.haiertvbic.tvnow.service.ServiceUtil;
import com.haiertvbic.tvnow.service.SwitchChanellCallback;
import com.haiertvbic.tvnow.util.AppManager;
import com.haiertvbic.tvnow.util.IsExit;
import com.haiertvbic.tvnow.util.LocateToast;
import com.haiertvbic.tvnow.util.ProduceThread;
import com.haiertvbic.tvnow.util.SLog;
import com.haiertvbic.tvnow.util.SetActivityView;

public class TVWAProgramStateActivity extends Activity {
	public Activity context = TVWAProgramStateActivity.this;
	private static final String TAG = null;
	protected static final int GET_PROSTATION_FAIL = 03;
	protected static final int GET_PROSTATION_SUC = 04;
	private static final int GET_LOCAL_CODE_FAIL = 05;

	private TextView cha_name;
	private TextView pro_name;
	private ListView pro_cha_list;
	private ProgressBar bar_on_cha;

	public static TextView showTime_3;
	public SingleHandler sHandler;
	private View view;

	private String pro_id;
	private String chaName;
	private ArrayList<ProgramBean> programList;
	private boolean isHide;
	private boolean canSwitch;
	private int currentCha = -200;
	private int switchCha = -200;
	private Handler handler;

	/**
	 * 
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_program_state_tvwa);
		view = SetActivityView.setActivityViewTvwa(getWindow(),
				getWindowManager());
		AppManager.activityList.add(this);

		Intent intent = getIntent();
		pro_id = intent.getStringExtra("PRO_ID");
		String s = intent.getStringExtra("PRO_NAME");
		s = s.replaceAll("[0-9]", "");
		chaName = s;
		SLog.v("fav", "获取的PROID----》" + pro_id + "---------------PRO_NAME"
				+ chaName);
		initView();

		getResultPre();
		sHandler = SingleHandler.returnHandler();
		sHandler.setTextView(showTime_3);
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {

				super.handleMessage(msg);
				switch (msg.what) {

				case GET_PROSTATION_FAIL:
					// 获取频道数据失败，消失加载数据进度条
					// progressDialog.dismiss();
					bar_on_cha.setVisibility(View.GONE);
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.get_pro_failed_try_again));
					break;
				case GET_PROSTATION_SUC:
					// 获取数据成功，适配显示数据，消失加载数据的进度条
					bar_on_cha.setVisibility(View.GONE);
					if (programList != null && programList.size() > 0) {
						pro_cha_list.setAdapter(new ProChaAdapter());
						canSwitch = true;
					}
					break;
				case GET_LOCAL_CODE_FAIL:
					// 获取地域码失败
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.get_local_code_failed));
					break;
				case 0:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.read_change_msg_failed));
					break;

				case 4004500:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.change_success));
					currentCha = switchCha;
					try {
						Thread.sleep(4000);
					} catch (InterruptedException e) {

						SLog.e("", e.toString());
					}
					break;

				case 4004501:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.channel_non_existent));
					break;

				case 4004502:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.please_connect_crb));
					break;

				case 4004503:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.no_set_crb));
					break;

				case -2002:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.connect_break_off));
					break;

				default:
					break;
				}
			}

		};
	}

	@Override
	protected void onPause() {

		super.onPause();
		isHide = true;

	}

	@Override
	protected void onResume() {

		super.onResume();
		if (isHide) {
			TVWAProgramListActivity.view.setVisibility(View.INVISIBLE);
		}
	}

	/**
	 * 初始化界面控件
	 */
	private void initView() {
		showTime_3 = (TextView) findViewById(R.id.show_time_3);
		cha_name = (TextView) findViewById(R.id.cha_name);
		pro_name = (TextView) findViewById(R.id.pro_name);
		pro_cha_list = (ListView) findViewById(R.id.pro_cha_list);
		bar_on_cha = (ProgressBar) findViewById(R.id.bar_on_cha);
		pro_name.setText(chaName);
		pro_cha_list.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				int chaId = programList.get(arg2).getCid();
				if (canSwitch && currentCha != chaId) {
					ServiceUtil.changeChannel(context, chaId,
							new SwitchChanellCallback() {
								@Override
								public void returnData(int source,
										int resultCode, int result) {
									handler.sendEmptyMessage(resultCode);
								}
							});
					switchCha = chaId;

				}

				ProduceThread.seconds = 60;
			}

		});
		pro_cha_list.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {

				ProduceThread.seconds = 60;

			}

			public void onNothingSelected(AdapterView<?> arg0) {

			}

		});
	}

	/**
	 * 按下按键时的反应
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		ProduceThread.seconds = 60;
		if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
			sHandler.setTextView(TVWAProgramListActivity.showTime_2);
			finish();
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			ProduceThread.canRun = false;
			ProduceThread.exit = false;
			IsExit.isExit(this);
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 填充的adapter，节目在其他频道播放的情况
	 * 
	 * @author sun
	 */
	public class ProChaAdapter extends BaseAdapter {

		public int getCount() {
			return programList.size();
		}

		public Object getItem(int position) {

			return null;
		}

		public long getItemId(int position) {

			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null)
				convertView = LayoutInflater.from(context).inflate(
						R.layout.layout_program_state_tvwa_item, null);
			TextView chaName = (TextView) convertView
					.findViewById(R.id.cha_name);
			TextView proName = (TextView) convertView
					.findViewById(R.id.pro_name);
			TextView staTime = (TextView) convertView
					.findViewById(R.id.start_time);
			TextView tomorrow = (TextView) convertView
					.findViewById(R.id.state_tomorrow_tvwa);
			ProgramBean p = programList.get(position);
			Calendar c = Calendar.getInstance();
			int week = c.getTime().getDay();
			if (week == 0) {
				week = 7;
			}
			if (programList != null && p != null) {
				chaName.setText(p.getCname());
				proName.setText(p.getPn());
				String s = p.getPstime() + "c";
				s = s.replace(":00c", "");
				if (p.getPweekday() == (week + 1)) {
					tomorrow.setText(context.getResources().getString(
							R.string.tomorrow));
					tomorrow.setVisibility(View.VISIBLE);
					staTime.setText(s);
				} else {
					tomorrow.setVisibility(View.GONE);
					staTime.setText(s);
				}
			}

			return convertView;
		}
	}

	// }

	/**
	 * 得倒节目在其他台播放的数据
	 */
	public void getResultPre() {
		new Thread() {
			public void run() {
				bar_on_cha.setVisibility(View.VISIBLE);
				LocalCodeBean loc_cod_bean = CAEProtocol.getLocalCode();
				if (loc_cod_bean == null) {
					handler.sendEmptyMessage(GET_LOCAL_CODE_FAIL);
				}

				if (loc_cod_bean.getReturn_code() == 4006301) {
					handler.sendEmptyMessage(GET_LOCAL_CODE_FAIL);
				} else {
					try {
						programList = EPGWeb.getSituation(context, pro_id,
								loc_cod_bean.getCity() + "");
					} catch (Exception e) {
						if (programList == null) {
							handler.sendEmptyMessage(GET_PROSTATION_FAIL);
						}
					}
					if (programList != null) {
						handler.sendEmptyMessage(GET_PROSTATION_SUC);
					} else {
						handler.sendEmptyMessage(GET_PROSTATION_FAIL);
					}
				}
			};
		}.start();

	}
}
